//
//  SubTableView.m
//  
//
//  Created by xu on 15/11/8.
//
//

#import "CollectTableView.h"
#import "BaseViewController.h"
#import "CollectViewController.h" 
#import "CollectCell.h"
#import "Util.h"
#import "UIImageView+WebCache.h"
#import "SJAvatarBrowser.h"
@implementation CollectTableView
{
    AFHTTPRequestOperationManager *_manager;
}

//  父类中已经添加了tableview的代理
-(void)initData{
    _nilArray = [[NSMutableArray alloc] init];
    _manager = [AFHTTPRequestOperationManager manager];
    NSString *url=[NSString stringWithFormat:@"%@chat/getCollection",BaseURL];
    NSDictionary *parameters = @{@"memberid":Getmemberid,@"size":@"20",@"endid":@"0"};
    AFHTTPRequestOperation*op= [_manager POST:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSError*error;
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
        NSData *jsonData = [[dic valueForKey:@"obj"] dataUsingEncoding:NSUTF8StringEncoding];
        NSArray *result  = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
        NSLog(@"%@",dic);
        if (error==nil&&![result isEqual:[NSNull null]]&&result!=nil&&result.count!=0) {
            for (int i = 0; i<[result count]; i++) {
                NSDictionary *c= result[i];
                [_nilArray addObject:c];
            }
        }
        [self reloadData];
        [self doneLoadingTableViewData];
        if ([_nilArray count]<20) {
            [self setIsLastPage:YES];
        }else{
            [self setIsLastPage:NO];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [[[UIAlertView alloc] initWithTitle: @"网络异常" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
        [self doneLoadingTableViewData];
    }];
    op.responseSerializer = [AFCompoundResponseSerializer serializer];
    [op start];
}

-(void)initLastData{
    if (_nilArray!=nil&&_nilArray.count>0) {
        
    
    NSDictionary *c =[_nilArray objectAtIndex:[_nilArray count]-1];
    _manager = [AFHTTPRequestOperationManager manager];
    NSString *url=[NSString stringWithFormat:@"%@chat/getCollection",BaseURL];
        _lastcid =[c valueForKey:@"id"];
    NSDictionary *parameters = @{@"memberid":Getmemberid,@"size":@"20",@"endid":_lastcid};
    AFHTTPRequestOperation*op= [_manager POST:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSError*error;
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
        NSData *jsonData = [[dic valueForKey:@"obj"] dataUsingEncoding:NSUTF8StringEncoding];
        NSArray *result  = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
        NSLog(@"%@",dic);
        if (error==nil&&![result isEqual:[NSNull null]]&&result!=nil&&result.count!=0) {
            for (int i = 0; i<[result count]; i++) {
                NSDictionary *data= result[i];
                
                [_nilArray addObject:data];
                 NSMutableArray *indexPathArray = [NSMutableArray array];
                NSIndexPath *tempIndexPath = [NSIndexPath indexPathForRow:i inSection:0];
                [indexPathArray addObject:tempIndexPath];
                 [self insertRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationNone];
                
            }
            if (result.count < 20) {
                [self setIsLastPage:YES];

            }else [self setIsLastPage:NO];
        }else{
            [self setIsLastPage:YES];
        }
        [self reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [[[UIAlertView alloc] initWithTitle: @"网络异常" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
    }];
    op.responseSerializer = [AFCompoundResponseSerializer serializer];
    [op start];
    }
}
//实现TABLE方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//    if (_nilArray==nil) {
//        return 0;
//    }
    return _nilArray.count;
}


//每个cell调用的方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CollectCell *cell = [CollectCell createWithTableView:tableView];
    for (UIView *view in [cell.content subviews]) {
        if (view.tag == 3000) {
            [view removeFromSuperview];
        }
    }
    if (_nilArray!=nil&&_nilArray.count>0) {
        NSDictionary *d = [_nilArray objectAtIndex:indexPath.row];
        cell.userName.text=d[@"name"];
        cell.time.text =d[@"collection_date"];
        NSString *headurl = [NSString stringWithFormat:@"%@%@",BaseImageURL,[d valueForKey:@"head"]];
        [cell.head sd_setImageWithURL:[NSURL URLWithString:headurl]];
        if (cell.head.image==nil) {
            [cell.head setImage:[UIImage imageNamed:@"head_pic"]];
        }
        NSNumber *type = d[@"collection_type"];
        if ([type isEqualToNumber:@1]) {
            cell.text.text = [d valueForKey:@"content"];
            cell.text.hidden = NO;
            cell.image.hidden = YES;
            CGRect rect = cell.frame;
            rect.size.height = 80+5;
            cell.frame = rect;
        }else if ([type isEqualToNumber:@0]){
            NSString * s =[d valueForKey:@"path"];
            cell.text.text = [d valueForKey:@"content"];
            cell.text.hidden = NO;
            
            if ([s isKindOfClass:[NSNull class]] || [s isEqualToString:@""] || [s isEqualToString:@"<null>"]) {
                CGRect rect = cell.frame;
                rect.size.height = 80+5;
                cell.frame = rect;
                cell.image.hidden = YES;
            }else{
                cell.image.hidden = YES;
                NSArray *imgArray =[s componentsSeparatedByString:@","];
                if (imgArray.count<=3) {
                    for (int i=0; i<imgArray.count; i++) {
                        UIImageView *cimg = [[UIImageView alloc] initWithFrame:CGRectMake(i*(100)+15, 80, 90, 90)];
                        cimg.tag = 3000;
                        NSString *str = imgArray[i];
                        NSString *imageurl = [NSString stringWithFormat:@"%@%@",BaseImageURL,str];
                        [cimg sd_setImageWithURL:[NSURL URLWithString:imageurl]];
                        if (cimg.gestureRecognizers.count == 0) {
                            cimg.userInteractionEnabled = YES;
                            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showImage:)];
                            [cimg addGestureRecognizer:tap];
                        }
                        [cell.content addSubview:cimg];
                    }
                    CGRect rect = cell.frame;
                    rect.size.height = 205;
                    cell.frame = rect;
                    cell.image.hidden = NO;
                }else if (imgArray.count>3&&imgArray.count<=6){
                    for (int i=0; i<3; i++) {
                        UIImageView *cimg = [[UIImageView alloc] initWithFrame:CGRectMake(i*(100)+15, 80, 90, 90)];
                        cimg.tag = 3000;

                        NSString *str = imgArray[i];
                        NSString *imageurl = [NSString stringWithFormat:@"%@%@",BaseImageURL,str];
                        [cimg sd_setImageWithURL:[NSURL URLWithString:imageurl]];
                        if (cimg.gestureRecognizers.count == 0) {
                            cimg.userInteractionEnabled = YES;
                            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showImage:)];
                            [cimg addGestureRecognizer:tap];
                        }
                        [cell.content addSubview:cimg];
                    }
                    for (int i=3; i<imgArray.count; i++) {
                        UIImageView *cimg = [[UIImageView alloc] initWithFrame:CGRectMake((i-3)*(100)+15, 180, 90, 90)];
                        NSString *str = imgArray[i];
                        cimg.tag = 3000;

                        NSString *imageurl = [NSString stringWithFormat:@"%@%@",BaseImageURL,str];
                        [cimg sd_setImageWithURL:[NSURL URLWithString:imageurl]];
                        if (cimg.gestureRecognizers.count == 0) {
                            cimg.userInteractionEnabled = YES;
                            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showImage:)];
                            [cimg addGestureRecognizer:tap];
                        }
                        [cell.content addSubview:cimg];
                    }
                    CGRect rect = cell.frame;
                    rect.size.height = 305;
                    cell.frame = rect;
                    cell.image.hidden = NO;
                }else if (imgArray.count>6){
                    for (int i=0; i<3; i++) {
                        UIImageView *cimg = [[UIImageView alloc] initWithFrame:CGRectMake(i*(100)+15, 80, 90, 90)];
                        NSString *str = imgArray[i];
                        cimg.tag = 3000;

                        NSString *imageurl = [NSString stringWithFormat:@"%@%@",BaseImageURL,str];
                        [cimg sd_setImageWithURL:[NSURL URLWithString:imageurl]];
                        if (cimg.gestureRecognizers.count == 0) {
                            cimg.userInteractionEnabled = YES;
                            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showImage:)];
                            [cimg addGestureRecognizer:tap];
                        }
                        [cell.content addSubview:cimg];
                    }
                  
                    for (int i=3; i<6; i++) {
                        UIImageView *cimg = [[UIImageView alloc] initWithFrame:CGRectMake((i-3)*(100)+15, 180, 90, 90)];
                        NSString *str = imgArray[i];
                        cimg.tag = 3000;

                        NSString *imageurl = [NSString stringWithFormat:@"%@%@",BaseImageURL,str];
                        [cimg sd_setImageWithURL:[NSURL URLWithString:imageurl]];
                        if (cimg.gestureRecognizers.count == 0) {
                            cimg.userInteractionEnabled = YES;
                            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showImage:)];
                            [cimg addGestureRecognizer:tap];
                        }
                        [cell.content addSubview:cimg];
                    }
                    for (int i=6; i<imgArray.count; i++) {
                        UIImageView *cimg = [[UIImageView alloc] initWithFrame:CGRectMake((i-6)*(100)+15, 280, 90, 90)];
                        cimg.tag = 3000;

                        NSString *str = imgArray[i];
                        NSString *imageurl = [NSString stringWithFormat:@"%@%@",BaseImageURL,str];
                        [cimg sd_setImageWithURL:[NSURL URLWithString:imageurl]];
                        if (cimg.gestureRecognizers.count == 0) {
                            cimg.userInteractionEnabled = YES;
                            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showImage:)];
                            [cimg addGestureRecognizer:tap];
                        }
                        [cell.content addSubview:cimg];
                    }
                    CGRect rect = cell.frame;
                    rect.size.height = 405;
                    cell.frame = rect;
                    cell.image.hidden = NO;
                }
//                NSString *str = [s componentsSeparatedByString:@","][0];
//                NSString *imageurl = [NSString stringWithFormat:@"%@%@",BaseImageURL,str];
//                [cell.image sd_setImageWithURL:[NSURL URLWithString:imageurl]];
//                if (cell.image.gestureRecognizers.count == 0) {
//                    cell.image.userInteractionEnabled = YES;
//                    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showImage:)];
//                    [cell.image addGestureRecognizer:tap];
//                }
                
            }
            
        }else if ([type isEqualToNumber:@2]){
            cell.text.hidden = YES;
            cell.image.hidden = NO;
            CGRect rect = cell.frame;
            rect.size.height = 195;
            cell.frame = rect;
            NSString *imageurl = [NSString stringWithFormat:@"%@%@",BaseImageURL,[d valueForKey:@"collection_content"]];
            [cell.image sd_setImageWithURL:[NSURL URLWithString:imageurl]];
//            if (cell.image.image==nil) {
//                //[cell.head setImage:[UIImage imageNamed:@"head_pic"]];
//            }
          //  himage.image = [self OriginImage:himage.image scaleToSize:CGSizeMake(105, 105)];
            if (cell.image.gestureRecognizers.count == 0) {
                cell.image.userInteractionEnabled = YES;
                
                UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showImage:)];
                [cell.image addGestureRecognizer:tap];
            }
        }
        
        [cell setNeedsDisplay];
        
    }
    return cell;
}
-(void)showImage:(UITapGestureRecognizer *)imageView{
    UIImageView* i =(UIImageView*) imageView.view;
    if (i.image!=nil) {
        [SJAvatarBrowser showImage:i];//调用方法
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
     NSDictionary *d = [_nilArray objectAtIndex:indexPath.row];
//    ZoomDetailViewController *vc = [[ZoomDetailViewController alloc] init];
//    NSNumber *tid =d[@"thread_id"];
//    if (![tid isEqualToNumber:@0]) {
//        vc.Id = tid;
//        [self.viewController.navigationController pushViewController:vc animated:YES];
//    }
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSString *url = [NSString stringWithFormat:@"%@chat/delCollection",BaseURL];
        NSURL *URL=[NSURL URLWithString:url];//不需要传递参数
        NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:URL];//默认为get请求
        request.timeoutInterval=5.0;//设置请求超时为5秒
        request.HTTPMethod=@"POST";//设置请求方法
        //设置请求体
        NSDictionary *d = [_nilArray objectAtIndex:indexPath.row];
        NSString *param=[NSString stringWithFormat:@"id=%@",d[@"id"]];
        //把拼接后的字符串转换为data，设置请求体
        request.HTTPBody=[param dataUsingEncoding:NSUTF8StringEncoding];
        NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        NSError *err;
        NSMutableDictionary * dic =[NSJSONSerialization JSONObjectWithData:received options:NSJSONReadingMutableContainers error:&err];
        NSString *data = dic[@"code"];
        if ([data isEqualToString:@"4000"]) {
            [_nilArray removeObjectAtIndex:indexPath.row];
            [self deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
            
        } else{
            [[[UIAlertView alloc] initWithTitle: @"删除失败" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
            
        }
        
    }
}



//-(UIImage*) OriginImage:(UIImage *)image scaleToSize:(CGSize)size
//{
//    UIGraphicsBeginImageContext(size);  //size 为CGSize类型，即你所需要的图片尺寸
//    
//    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
//    
//    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
//    
//    UIGraphicsEndImageContext();
//    
//    return scaledImage;   //返回的就是已经改变的图片
//}
//- (UIImage *)getPartOfImage:(UIImage *)img rect:(CGRect)partRect
//{
//    CGImageRef imageRef = img.CGImage;54

//    CGImageRef imagePartRef = CGImageCreateWithImageInRect(imageRef, partRect);
//    UIImage *retImg = [UIImage imageWithCGImage:imagePartRef];
//    CGImageRelease(imagePartRef);
//    return retImg;
//}

@end
